/**
 * Copyright (c) 2012-2014 All Rights Reserved.
 */
package com.easy.framwork.connection;

import java.sql.Connection;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.easy.framwork.FrameworkHolder;

/**
 * 
 * @author wy
 * @version v 0.1 2014-1-1 下午5:48:13 wy Exp $
 */
public class ConnectionHolder {

    private final static Logger log = LoggerFactory.getLogger(ConnectionHolder.class);

    private final ThreadLocal<Connection> CONN_TL = new ConnectionThreadLocal();

    /**
     * 获取数据源链接
     * 
     * @return
     */
    public Connection getConnection() {
        return CONN_TL.get();
    }

    /**
     * 移除
     */
    public void removeConnection() {
        CONN_TL.remove();
    }

    /**
     * 数据源存储
     * 
     * @author wy
     * @version v 0.1 2014-1-1 下午5:53:24 wy Exp $
     */
    class ConnectionThreadLocal extends ThreadLocal<Connection> {

        /**
         * @see java.lang.ThreadLocal#initialValue()
         */
        @Override
        protected Connection initialValue() {
            try {
                return FrameworkHolder.getInstance().getDataSource().getConnection();
            }
            catch (SQLException e) {
                log.error("get connection from datasource error", e);
            }
            return null;
        }
    }

}
